import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { app, BrowserWindow } from "electron";
import path from "path";
const NODE_ENV = process.env.NODE_ENV
import {  ipcMain} from 'electron'

const serverJarPath = "/assets/runtime/CodeGenerateServer.jar";
const javaExePath = "/assets/runtime/jre/bin/java.exe";

const SERVER_JAR_PATH = path.join(getResourcesPath(), serverJarPath);
const JAVA_EXE_PATH = path.join(getResourcesPath(), javaExePath);

function getResourcesPath(): string {
  let resourcesPath = app.getAppPath()
  if (NODE_ENV !== 'development') {
    resourcesPath = path.dirname(app.getPath("exe"))+"/resources"
  }
  return resourcesPath;
}

let ls: ChildProcessWithoutNullStreams|null ;

let outputWindow:BrowserWindow|null = null;

function safeRun(win:BrowserWindow|null, run: (win:BrowserWindow) => void ) {
  if (win && !win.isDestroyed()) {
    run(win);
  }
}

export function startServer(preloadWindow: BrowserWindow, port: string = "8080") {
  if (ls)return
  ipcMain.on('server:listen', (event) => {
    if (outputWindow == null) {
      outputWindow = BrowserWindow.fromWebContents(event.sender)
    }
  })
  ipcMain.on('server:un-listen', () => {
    if (outputWindow) {
      outputWindow == null
    }
  })
  ls = spawn(JAVA_EXE_PATH, ['-jar', SERVER_JAR_PATH, '-Dserver.port', port])
  ls.stdout.on('data', (data) => {
    safeRun(outputWindow, win => win.webContents.send('server:data-success', data.toString('utf-8')))
    safeRun(preloadWindow, win => win.webContents.send('server:data-success', data.toString('utf-8')))
    if (data.toString("utf-8").includes("Start Code Generator Application")) {
      safeRun(outputWindow, win => win.webContents.send('server:ready'))
      safeRun(preloadWindow, win => win.webContents.send('server:ready'))
    }
  });
  ls.stderr.on('data', (data) => {
    safeRun(outputWindow, win => win.webContents.send('server:data-error', data.toString('utf-8')))
    safeRun(preloadWindow, win => win.webContents.send('server:data-error', data.toString('utf-8')))
  });
  ls.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
}

export function killServer() {
  if (!ls) return
  ls.kill()
  ls = null
}

